package com.open.server;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.tmt.v20180321.TmtClient;
import com.tencentcloudapi.tmt.v20180321.models.TextTranslateRequest;
import com.tencentcloudapi.tmt.v20180321.models.TextTranslateResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author tanyongpeng
 * <p>文本翻译服务</p>
 **/
@Component
@Slf4j
public class TextTranslateServer {

    @Value("${tencentcloudapi.secretId}")
    private String secretId;
    @Value("${tencentcloudapi.secretKey}")
    private String secretKey;
    @Value("${tencentcloudapi.text.endpoint}")
    private String endpoint;
    @Value("${tencentcloudapi.text.region}")
    private String region;

    /**
     *  文本翻译服务，官方文档：https://cloud.tencent.com/document/product/551/15612
     * @param prompt
     * @return
     */
    public String textTranslate(String prompt){
        try{
            Credential cred = new Credential(secretId, secretKey);
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint(endpoint);
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            TmtClient client = new TmtClient(cred, region, clientProfile);
            TextTranslateRequest req = new TextTranslateRequest();
            req.setSourceText(prompt);
            req.setSource("auto");
            req.setTarget("en");
            req.setProjectId(0L);
            TextTranslateResponse resp = client.TextTranslate(req);
            JSONObject jsonObject = JSONUtil.parseObj(TextTranslateResponse.toJsonString(resp));
            return jsonObject.getStr("TargetText");
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            return "";
        }
    }

}
